package com.asimplefox.configs;

import io.github.kloping.file.FileUtils;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;

/**
 * @author github.kloping
 */
@Component
public class FileConfig {

    @Value("${server.pre}")
    public String serverPre;

    private String mergeUrl(String name) {
        return serverPre + name;
    }

    @Value("${file.dir}")
    public String fileDir;

    /**
     * @param dir  不加前缀 /
     * @param name
     * @return
     */
    public FileWithPath getFileWithPath(String dir, String name) {
        FileWithPath fwp = new FileWithPath();
        fwp.dir = dir;
        fwp.name = name;
        fwp.file = new File(fileDir, fwp.dir + fwp.name);
        fwp.file.getParentFile().mkdirs();
        fwp.path = fwp.file.getAbsolutePath();
        fwp.url = mergeUrl(fwp.dir + fwp.name);
        return fwp;
    }

    public void del(String url) {
        String filep = url.replace(serverPre, "");
        File file = new File(fileDir, filep);
        file.delete();

        filep = url.replace(serverPre, "").replace(".mp4", ".wav");
        file = new File(fileDir, filep);
        if (file.exists()) file.delete();

        filep = url.replace(serverPre, "").replace(".mp4", ".json");
        file = new File(fileDir, filep);
        if (file.exists()) file.delete();
    }

    public void delAndDir(String url) {
        String filep = url.replace(serverPre, "");
        File file = new File(fileDir, filep);
        file.delete();
        file.getParentFile().delete();
    }

    @Getter
    public static class FileWithPath {
        private String url;
        private String path;
        private String name;
        private String dir;
        private File file;

        public boolean write(byte[] bytes) {
            try {
                FileUtils.testFile(file);
                FileUtils.writeBytesToFile(bytes, file);
                return true;
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
        }

    }
}
